package org.budo.dubbo.protocol.http.authentication;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.budo.jdbc.dao.BudoJdbcDao;
import org.budo.jdbc.dao.impl.BudoJdbcDaoImpl;
import org.budo.support.mvcs.Mvcs;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
@Getter
@Setter
public class BudoJdbcSessionAuthenticationCheckService implements AuthenticationCheckService {
    private static final String SQL = "SELECT user_id FROM t_token WHERE text=?";

    private DataSource dataSource;

    @Override
    public Serializable getAuthenticationPrincipal() {
        HttpServletRequest request = Mvcs.getRequest();
        if (null == request) {
            log.error("#21 Mvcs.getRequest returns null");
            return null;
        }

        String token = request.getParameter("_token");
        if (null == token || token.isEmpty() || "null".equalsIgnoreCase(token) || "undefined".equalsIgnoreCase(token)) {
            token = Mvcs.getRequestCookieValue(request, "_token");
        }

        if (null == token || token.isEmpty() || "null".equalsIgnoreCase(token) || "undefined".equalsIgnoreCase(token)) {
            log.debug("#41 TOKEN_EMPTY, token = {}, request = {}", token, request);
            return Fail.TOKEN_EMPTY;
        }

        BudoJdbcDao jdbcDao = new BudoJdbcDaoImpl(this.getDataSource());
        Object authenticationPrincipal = jdbcDao.findIntegerBySql(SQL, new Object[] { token });

        if (null == authenticationPrincipal) {
            return Fail.TOKEN_NOT_FOUND;
        }

        return (Serializable) authenticationPrincipal;
    }
}